package com.zerowidth.moc.web.controller.serviceimpl;

import com.zerowidth.db.bean.*;
import com.zerowidth.db.op.*;
import com.zerowidth.db.utils.TimeUtils;
import com.zerowidth.moc.web.Global;
import com.zerowidth.moc.web.auth.TokenHelper;
import com.zerowidth.moc.web.bean.MockBean;
import com.zerowidth.moc.web.controller.service.MockService;
import com.zerowidth.moc.web.resp.ResCode;
import com.zerowidth.moc.web.resp.ResultBean;
import com.zerowidth.moc.web.resp.helper.ResponseCreator;
import com.zerowidth.moc.web.utils.CollectionUtils;
import com.zerowidth.moc.web.utils.LogUtil;
import com.zerowidth.moc.web.utils.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Service
public class MockServiceImpl implements MockService {

    private static final int MAX_SHARE_COUNT = 3;

    private static List<VersionBean> versionBeanList = null;
    private static long lastReadVersionTime = 0;

    @Override
    public ResponseEntity<ResultBean<Boolean>> check(
            HttpServletRequest request,
            String stat_id, String user_id,
            String brand, String model, String manufacturer,
            String android_version,
            String app_sign_key) {

        if (StringUtils.isEmpty(app_sign_key)) {
            return ResponseCreator.creatOk(true, ResCode.CODE_ERR_UNKNOWN, "");
        }


        if (StringUtils.isNotBlank(user_id)) {
            //校验此 userId 的登录信息是否正确，防止多机登录
            String token = TokenHelper.getRequestToken();
            AuthTokenBean authTokenBean = AuthTokenDB.findUserByToken(token);
            if (authTokenBean == null) {
                //userId 和 token 不匹配
                return ResponseCreator.creatOk(true, ResCode.ER_1003, "登录已失效，请重新登录");
            }
        }

        String appVersionName = request.getHeader("appVersionName");
        LogUtil.e("appVersionName = " + appVersionName);

        if (!StringUtils.contains(Global.APP_VERSION_LIST, appVersionName)){
            //不是这些版本的用户，直接强行关闭APP进程
            return ResponseCreator.creatOk(false, ResCode.CODE_OK, "");
        }

        String app_channel = request.getHeader("channel");
        String client_os = request.getHeader("os");
        String ip = request.getRemoteAddr();

        if (CollectionUtils.isEmpty(versionBeanList)) {

            if (System.currentTimeMillis() - lastReadVersionTime > 12 * 60 * 60 * 1000) {
                LogUtil.e("从数据库中读取最新版本信息");
                lastReadVersionTime = System.currentTimeMillis();
                versionBeanList = VersionDB.getNewVersionList(appVersionName, app_channel, appVersionName);
            }

        }


        if (CollectionUtils.isNotEmpty(versionBeanList)) {

            boolean forceUpdate = false;
            for (int i = 0; i < CollectionUtils.size(versionBeanList); i++) {
                if (versionBeanList.get(i).force_update) {
                    forceUpdate = true;
                    break;
                }
            }

            if (forceUpdate) {
                return ResponseCreator.creatOk(null, ResCode.ER_70103, "旧版本已停止服务，请更新到最新版本");
            }
        }

        if (StringUtils.isEmpty(user_id)) {
            user_id = "";
        }

        MockStatBean mockStatBean = MockStatUserDB.findUserDB(stat_id, user_id);
        if (mockStatBean == null) {
            //没有访客记录，首次使用

            String first_use_time = TimeUtils.convert(System.currentTimeMillis(), TimeUtils.TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);
            String create_time = first_use_time;
            String update_time = first_use_time;

            long freeDayMillisecond = (long)(2 * 60 * 60 * 1000);
            String free_trial_end_time = TimeUtils.convert(System.currentTimeMillis() + freeDayMillisecond,
                    TimeUtils.TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);

            MockStatUserDB.insertDB(stat_id, user_id, first_use_time, create_time, update_time, free_trial_end_time,
                    brand, model, manufacturer, android_version, appVersionName, app_channel, client_os, ip, app_sign_key);

            return ResponseCreator.creatOk(true, ResCode.CODE_OK, "欢迎使用");
        } else {

            //统计数据
            if (StringUtils.isEmpty(user_id)) {
                //没有登录时，根据statId来更新
                MockStatUserDB.updateUserStat(stat_id, appVersionName, app_channel, client_os, ip, app_sign_key);
            } else {
                //已登录，根据userId来更新，需要时刻更新最新设备，以便判断绑定设备
                MockStatUserDB.updateUserStat2(user_id, brand, model, appVersionName, app_channel, client_os, ip, app_sign_key);
            }

            if (StringUtils.isEmpty(mockStatBean.user_id) && StringUtils.isNotEmpty(user_id)) {
                MockStatUserDB.updateUserIdByStatId(stat_id, user_id, app_sign_key);
            }

            //有访客记录，非首次使用
            String nowTime = TimeUtils.convert(System.currentTimeMillis(), TimeUtils.TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);
            if (StringUtils.compare(nowTime, mockStatBean.free_trial_end_time) < 0) {
                //仍在访客体验期

                return ResponseCreator.creatOk(true, ResCode.CODE_OK, "欢迎使用.");
            } else {
                //超出访客体验期
                if (StringUtils.isNotEmpty(user_id)) {
                    //此用户 已登录

                    UserBean userBean = UserDB.findUserByUserId(user_id);
                    if (userBean == null || StringUtils.isEmpty(userBean.vip_end_time)) {
                        if (mockStatBean.share_count < MAX_SHARE_COUNT) {
                            return ResponseCreator.creatOk(null, ResCode.ER_70102,
                                    "免费体验已到期，购买vip后可以无限使用。\n\n分享app到10人以上的群聊，可以获得额外一天的体验期。每个用户可以奖励3次");
                        }
                        if (appVersionName.compareTo("3.0.0") < 0) {
                            //客户端是 3.0.0 以前的版本
                            return ResponseCreator.creatOk(null, ResCode.ER_70100, "免费体验已到期，购买vip后可以无限使用.");
                        } else {
                            //客户端是 3.0.0 及其以后的版本
                            return ResponseCreator.creatOk(null, ResCode.ER_70102,
                                    "免费体验已到期，购买vip后可以无限使用。\n\n分享app到10人以上的群聊，可以获得额外一天的体验期。每个用户可以奖励3次");
                        }
                    } else if (StringUtils.compare(nowTime, userBean.vip_end_time) < 0) {
                        //已登录，且在会员有效期内
                        return ResponseCreator.creatOk(true, ResCode.CODE_OK, "欢迎使用..");
                    } else {
                        //已登录，已超出会员有效期
                        return ResponseCreator.creatOk(null, ResCode.ER_70101, "会员已到期，购买vip后可以无限使用，user_id = " + user_id);
                    }
                } else {
                    //此用户 未登录

                    if (mockStatBean.share_count < MAX_SHARE_COUNT) {
                        if (appVersionName.compareTo("3.0.0") < 0) {
                            //客户端是 3.0.0 以前的版本
                            return ResponseCreator.creatOk(null, ResCode.ER_70102,
                                    "免费体验已到期，购买vip后可以无限使用。\n\n分享app到10人以上的群聊，可以获得额外一天的体验期。每个用户可以奖励3次");
                        } else {
                            //客户端是 3.0.0 及其以后的版本
                            return ResponseCreator.creatOk(null, ResCode.ER_70102,
                                    "免费体验已到期，购买vip后可以无限使用。\n\n分享app到10人以上的群聊，可以获得额外一天的体验期。每个用户可以奖励3次");

                        }
                    } else {
                        return ResponseCreator.creatOk(null, ResCode.ER_70100, "免费体验已到期，购买vip后可以无限使用.");
                    }
                }
            }
        }

    }

    @Override
    public ResponseEntity<ResultBean<MockBean>> check2(HttpServletRequest request,
                                                       String stat_id, String user_id, String brand,
                                                       String model, String manufacturer, String android_version,
                                                       String app_sign_key, String longitude, String latitude) {

        if (StringUtils.isEmpty(app_sign_key)) {
            return ResponseCreator.creatOk(null, ResCode.CODE_ERR_UNKNOWN, "");
        }

        if (StringUtils.isNotBlank(user_id)) {
            //校验此 userId 的登录信息是否正确，防止多机登录
            String token = TokenHelper.getRequestToken();
            AuthTokenBean authTokenBean = AuthTokenDB.findUserByToken(token);
            if (authTokenBean == null) {
                //userId 和 token 不匹配
                return ResponseCreator.creatOk(null, ResCode.ER_1003, "登录已失效，请重新登录");
            }
        }

        String appVersionName = request.getHeader("appVersionName");
        String appName = request.getHeader("appName");
        String app_channel = request.getHeader("channel");
        String client_os = request.getHeader("os");
        String ip = request.getRemoteAddr();

        if (StringUtils.isNotEmpty(user_id)) {
            UserDB.updateUpdateTimeByUserId(user_id);
        }

        List<VersionBean> versionBeanList = VersionDB.getNewVersionList(appVersionName, app_channel, appVersionName);

        if (CollectionUtils.isNotEmpty(versionBeanList)) {

            boolean forceUpdate = false;
            for (int i = 0; i < CollectionUtils.size(versionBeanList); i++) {
                if (versionBeanList.get(i).force_update) {
                    forceUpdate = true;
                    break;
                }
            }

            if (forceUpdate) {
                return ResponseCreator.creatOk(null, ResCode.ER_70103, "旧版本已停止服务，请更新到最新版本");
            }
        }

        if (StringUtils.isEmpty(user_id)) {
            user_id = "";
        }


        String appNameEncode = null;
        try {
            appNameEncode = URLEncoder.encode("顺丰定位", "utf-8");
            if (StringUtils.equals(appNameEncode, appName)) {
                //是顺丰定位APP

                UserBean userBean = UserDB.findUserByUserId(user_id);

                if (userBean == null || userBean.vip_type != 7) {
                    return ResponseCreator.creatOk(null, ResCode.ER_70103, "购买钉钉专属会员后才可以使用此功能.");
                }
                if (userBean != null && userBean.dingding_pkg_version == 0) {
                    return ResponseCreator.creatOk(null, ResCode.ER_70104, "购买钉钉安全包后才可以正常使用不被检测.");
                }
            }
        } catch (UnsupportedEncodingException e) {

        }


        MockStatBean mockStatBean = MockStatUserDB.findUserDB(stat_id, user_id);
        if (mockStatBean == null) {
            //没有访客记录，首次使用

            String first_use_time = TimeUtils.convert(System.currentTimeMillis(), TimeUtils.TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);
            String create_time = first_use_time;
            String update_time = first_use_time;

            long freeDayMillisecond = (long)(0.5 * 24 * 60 * 60 * 1000);

            try {
                if (StringUtils.equals(appName, URLEncoder.encode("鹰眼定位", "utf-8"))) {
                    //鹰眼定位新用户，给予7天试用
                    freeDayMillisecond = (long)(7 * 24 * 60 * 60 * 1000);
                }
            } catch (UnsupportedEncodingException e) {

            }

            String free_trial_end_time = TimeUtils.convert(System.currentTimeMillis() + freeDayMillisecond,
                    TimeUtils.TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);

            MockStatUserDB.insertDB(stat_id, user_id, first_use_time, create_time, update_time, free_trial_end_time,
                    brand, model, manufacturer, android_version, appVersionName, app_channel, client_os, ip, app_sign_key);

            MockBean mockBean = new MockBean();
            mockBean.f = true;
            mockBean.lo = Double.parseDouble(longitude);
            mockBean.la = Double.parseDouble(latitude);

            return ResponseCreator.creatOk(mockBean, ResCode.CODE_OK, "欢迎使用");
        } else {

            //统计数据
            if (StringUtils.isEmpty(user_id)) {
                //没有登录时，根据statId来更新
                MockStatUserDB.updateUserStat(stat_id, appVersionName, app_channel, client_os, ip, app_sign_key);
            } else {
                //已登录，根据userId来更新，需要时刻更新最新设备，以便判断绑定设备
                MockStatUserDB.updateUserStat2(user_id, brand, model, appVersionName, app_channel, client_os, ip, app_sign_key);
            }

            if (StringUtils.isEmpty(mockStatBean.user_id) && StringUtils.isNotEmpty(user_id)) {
                MockStatUserDB.updateUserIdByStatId(stat_id, user_id, app_sign_key);
            }

            //有访客记录，非首次使用
            String nowTime = TimeUtils.convert(System.currentTimeMillis(), TimeUtils.TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);
            if (StringUtils.compare(nowTime, mockStatBean.free_trial_end_time) < 0) {
                //仍在访客体验期

                MockBean mockBean = new MockBean();
                mockBean.f = true;
                mockBean.lo = Double.parseDouble(longitude);
                mockBean.la = Double.parseDouble(latitude);

                return ResponseCreator.creatOk(mockBean, ResCode.CODE_OK, "欢迎使用.");
            } else {
                //超出访客体验期
                if (StringUtils.isNotEmpty(user_id)) {
                    //此用户 已登录

                    UserBean userBean = UserDB.findUserByUserId(user_id);

                    if (userBean == null || StringUtils.isEmpty(userBean.vip_end_time)) {
                        if (mockStatBean.share_count < MAX_SHARE_COUNT) {
                            return ResponseCreator.creatOk(null, ResCode.ER_70102,
                                    "免费体验已到期，购买vip后可以无限使用。\n\n分享app到10人以上的群聊，可以获得额外一天的体验期。每个用户可以奖励3次");
                        }
                        if (appVersionName.compareTo("3.0.0") < 0) {
                            //客户端是 3.0.0 以前的版本
                            return ResponseCreator.creatOk(null, ResCode.ER_70100, "免费体验已到期，购买vip后可以无限使用.");
                        } else {
                            //客户端是 3.0.0 及其以后的版本
                            return ResponseCreator.creatOk(null, ResCode.ER_70102,
                                    "免费体验已到期，购买vip后可以无限使用。\n\n分享app到10人以上的群聊，可以获得额外一天的体验期。每个用户可以奖励3次");
                        }
                    } else if (StringUtils.compare(nowTime, userBean.vip_end_time) < 0) {
                        //已登录，且在会员有效期内

                        MockBean mockBean = new MockBean();
                        mockBean.f = true;
                        mockBean.lo = Double.parseDouble(longitude);
                        mockBean.la = Double.parseDouble(latitude);
                        return ResponseCreator.creatOk(mockBean, ResCode.CODE_OK, "欢迎使用..");
                    } else {
                        //已登录，已超出会员有效期
                        return ResponseCreator.creatOk(null, ResCode.ER_70101, "会员已到期，购买vip后可以无限使用，user_id = " + user_id);
                    }
                } else {
                    //此用户 未登录
                    if (mockStatBean.share_count < MAX_SHARE_COUNT) {
                        return ResponseCreator.creatOk(null, ResCode.ER_70102,
                                "免费体验已到期，购买vip后可以无限使用。\n\n分享app到10人以上的群聊，可以获得额外一天的体验期。每个用户可以奖励3次");
                    } else {
                        return ResponseCreator.creatOk(null, ResCode.ER_70100, "免费体验已到期，购买vip后可以无限使用.");
                    }
                }
            }
        }

    }

    @Override
    public ResponseEntity<ResultBean<Boolean>> shareAward(String stat_id, String user_id) {
        if (StringUtils.isEmpty(user_id)) {
            user_id = "";
        }

        MockStatBean mockStatBean = MockStatUserDB.findUserDB(stat_id, user_id);

        if (mockStatBean == null) {
            return ResponseCreator.creatOk(null, ResCode.ER_80000, "您不符合领取奖励的条件");
        } else if (mockStatBean.share_count >= 3) {
            return ResponseCreator.creatOk(null, ResCode.ER_80001, "每个用户最多可领取三次分享奖励");
        } else {
            if (MockStatUserDB.modifyShareAward(stat_id, user_id)) {
                return ResponseCreator.creatOk(null, ResCode.CODE_OK, "成功领取体验奖励");
            }
        }

        return null;
    }

    @Override
    public ResponseEntity<ResultBean<Boolean>> collect(HttpServletRequest request, String name,
                                                       String stat_id, String user_id,
                                                       String lat, String lng, String zoom) {
        if (CollectDB.insert(name, stat_id, user_id, lat, lng, zoom) > 0) {
            return ResponseCreator.creatOk(true, ResCode.CODE_OK, "收藏成功");
        } else {
            return ResponseCreator.creatOk(true, ResCode.ER_90000, "收藏失败");
        }
    }

    @Override
    public ResponseEntity<ResultBean<Boolean>> deleteCollect(HttpServletRequest request, String id) {
        if (CollectDB.delete(id) > 0) {
            return ResponseCreator.creatOk(true, ResCode.CODE_OK, "删除成功");
        }
        return ResponseCreator.creatOk(true, ResCode.CODE_OK, "删除失败");
    }

    @Override
    public ResponseEntity<ResultBean<List<CollectBean>>> getCollectList(HttpServletRequest request, String stat_id, String user_id) {

        List<CollectBean> beanList = CollectDB.find(stat_id, user_id);

        if (beanList == null) {
            return ResponseCreator.creatOk(null, ResCode.ER_90010, "获取收藏列表失败");
        }

        return ResponseCreator.creatOk(beanList, ResCode.CODE_OK, "获取收藏列表成功");
    }

    @Override
    public ResponseEntity<ResultBean<List<TeachBean>>> getTeachList(HttpServletRequest request) {

        List<TeachBean> beanList = TeachDB.getTeachList();

        return ResponseCreator.creatOk(beanList, ResCode.CODE_OK, "获取视频教程成功");
    }

    @Override
    public ResponseEntity<ResultBean<List<ProblemBean>>> getProblemList(HttpServletRequest request) {

        List<ProblemBean> beanList = ProblemDB.getProblemList();

        return ResponseCreator.creatOk(beanList, ResCode.CODE_OK, "获取视频教程成功");
    }

}
